<template>
  <view class="payment-container">
    <u-overlay :show="showzhezhao" @click="zhezhao"></u-overlay>
    <view class="merchant-info">
      <image class="merchant-avatar" :src="imgurl + formData.merAvatar" alt=""> </image>
      <text class="merchant-name font-bold">{{ formData.merName }}</text>
    </view>
    <view class="payment-input" @tap="openkeyboard">
      <text class="font-large">￥</text>
      <input class="input-field font-large" v-model="payPrice" type="number" placeholder="输入付款金额" @focus="openkeyboard" readonly disabled />
      <cu-keyboard ref="cukeyboard" @change="changeKeybord" @confirm="handleClose"></cu-keyboard>
    </view>

    <view class="remark-input">
      <input class="input-field" v-model="mark" placeholder="备注" @focus="closeKeyboard()" />
    </view>
    <view class="discount-details">
      <!--      <view class="discount-item">
        <text class="discount-title">折扣方式</text>
        <text class="discount-value">{{}}</text>
      </view> -->
      <view class="discount-item">
        <text class="discount-title">获取积分</text>
        <text class="discount-value">{{ earnPoints }}</text>
      </view>
      <view class="discount-item">
        <text class="discount-title" :class="fonthui">积分余额</text>
        <text class="discount-value">{{ priceConfig.points }}</text>
      </view>
      <view class="discount-item">
        <text class="discount-title">使用积分</text>
        <text class="discount-value">{{ availablePoints.toFixed(2) }}</text>
      </view>
      <view class="discount-item">
        <text class="discount-title">抵扣金额</text>
        <text class="discount-value">￥{{ (availablePoints / priceConfig.integralPropertyConversion).toFixed(2) }}</text>
      </view>
      <view class="discount-item">
        <text class="discount-title">付款方式</text>
        <text class="discount-value">{{ getPayTypeName(orderType) }}</text>
      </view>
      <view class="total-amount">
        <text class="total-label">小计</text>
        <text class="total-value font-large">￥{{ (earnPoints - availablePoints / priceConfig.integralPropertyConversion).toFixed(2) }}</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getUserInfo, programlogin } from "../../../utils/request_api.js"; /* 登录界面挪动接口 */
import { notBindingPhone } from "../../../utils/api/api.js";
import cukeyboard from "../../../components/cu-keyboard/cu-keyboard.vue";
import { getMerInfoByid, fastPaymentDiscountMethod, fastPayment } from "../../../utils/api/local";
import { IMG_URL } from "../../../config/index";
import { getDicts } from "../../../utils/request_sh";
export default {
  components: {
    cukeyboard,
  },
  watch: {},
  data() {
    return {
      showzhezhao: false,
      imgurl: IMG_URL,
      jifen: 0,
      mark: "",
      loading: false,
      allPrice: 0,
      availablePoints: 0,
      showKeyboard: false,
      payPrice: "",
      userInfo: "",
      formData: {},
      priceConfig: {
        type: 1,
        deductNum: 3,
        deductionRatio: 0.05,
        proportion: 80,
        points: "",
        offlineDeductionPropertyType: 1,
        integralPropertyConversion: 100,
        offlineIntegralProperty: 0,
        offlineIntegralDeductionPropertyValue: 0,
      },
      earnPoints: 0,
      ebMerId: "",
      orderType: "pay_ls",
      fanli: "",
    };
  },
  onShow() {},
  onLoad(option) {
    this.openkeyboard();
    if (option.id) {
      this.ebMerId = option.id;
      this.userType = 1;
    } else {
      const q = decodeURIComponent(option.q); // 获取到二维码原始链接内容
      console.log(q);
      this.ebMerId = q.split("/")[q.split("/").length - 1].split("-")[0];
      this.userType = q.split("/")[q.split("/").length - 1].split("-")[1];
      console.log(this.ebMerId);
      const scancode_time = parseInt(option.scancode_time); // 获取
    }

    this.getMerInfoByids(this.ebMerId);
    this.$nextTick(() => {
      this.initUser();
      // this.logggggin();
      // this.handleClose();
      // this.showloginJs();
    });
  },
  methods: {
    initUser() {
      uni.showLoading();
      getUserInfo()
        .then((res) => {
          if (res.code === 401) {
            this.showloginJs();
          } else {
            this.userInfo = res.data;
            uni.setStorageSync("userInfo", res.data);

            this.fastPaymentDiscountMethods(this.ebMerId);
            this.aaaa = true;
            uni.hideLoading();
            this.showzhezhao = false;
          }
        })
        .catch((err) => {
          console.error("获取用户信息失败", err);
          uni.hideLoading();
        });
    },
    showloginJs() {
      let that = this;
      uni.login({
        provider: "weixin",
        success: (res) => {
          if (res.code) {
            that.autoLogin(res.code);
          } else {
            uni.hideLoading();
            console.error("登录失败:", res.errMsg);
            uni.showToast({
              title: "微信登录失败，请稍后再试",
              icon: "none",
            });
          }
        },
        fail: (err) => {
          console.error("登录失败:", err);
          uni.showToast({
            title: "微信登录失败，请稍后再试",
            icon: "none",
          });
        },
      });
    },
    /* 免登录-每个界面调用 */
    async autoLogin(code) {
      let that = this;
      wx.getUserInfo({
        success(res) {
          const { nickName, avatarUrl, gender } = res.userInfo;
          programlogin({ code, avatar: avatarUrl, nickName, sex: gender }).then((response) => {
            const data = response.data;
            console.log("🚀 ~ programlogin ~ data:", data);
            that.authKey = data.key;
            that.openIdadw = data.openId;
            if (data.type === "login") {
              uni.setStorageSync("uid", data.uid);
              uni.setStorageSync("token", data.token);
              uni.setStorageSync("userInfo_data", data);
              uni.setStorageSync("openID", data.key);
              that.initUser();
              uni.hideLoading();
            } else {
              that.initUserregister();
            }
          });
        },
        fail: () => {
          uni.showToast({
            title: "您需要授权，才能获取您的信息！",
          });
        },
      });
    },
    initUserregister() {
      var params = {
        key: this.authKey,
        type: "routine",
        openId: this.openIdadw,
        phone: "",
        password: "",
        captcha: "",
        codeOrPassword: "3",
        inviterLinkId: this.ebMerId ? this.ebMerId : "",
        inviteeType: this.userType,
      };
      notBindingPhone(params).then((res) => {
        uni.hideLoading();
        if (res.code == 200) {
          const data = res.data;
          uni.setStorageSync("uid", data.uid);
          uni.setStorageSync("token", data.token);
          uni.setStorageSync("userInfo_data", data);
          uni.setStorageSync("openID", this.authKey);
          this.initUser();
        }
      });
    },
    getGetfanli() {
      getDicts("ptfl").then((response) => {
        const data = response.data;
        this.fanli = data[0].dictValue;
      });
    },
    zhezhao() {
      this.showzhezhao = false;
    },
    /* 登录界面挪动接口结束 */
    closeKeyboard() {
      this.$refs.cukeyboard.close();
    },
    changeKeybord(aa) {
      this.payPrice = aa;
      this.earnPoints = aa;
      // 默认可抵扣积分为0
      var availablePoints = 0;
      // 可使用积分   抵扣比例 * 抵扣金额
      var PointsCanBeUsed = this.priceConfig.integralPropertyConversion * this.priceConfig.offlineIntegralDeductionPropertyValue;
      // 当前账号总可使用补贴 换算金额  总积分 / 抵扣比例
      var keyongjif = (this.priceConfig.points / this.priceConfig.offlineIntegralDeductionPropertyValue).toFixed(2);
      var bilizongdikou = this.payPrice * this.priceConfig.offlineIntegralProperty * this.priceConfig.integralPropertyConversion;
      console.log(keyongjif);
      // 如果当前积分大于 换算比例    确保必须大于1 元的折扣
      if (this.priceConfig.points >= this.priceConfig.integralPropertyConversion) {
        // 如果为固定值模式
        if (this.priceConfig.offlineDeductionPropertyType == 1) {
          // 如果当然输入金额小于等于 抵扣金额  确定不可0元购买
          if (this.payPrice <= this.priceConfig.offlineIntegralDeductionPropertyValue) {
            availablePoints = 0;
          } else {
            // 如果 商家配置的换算比例 * 抵扣金额 小于总积分时 直接使用最高可抵扣的积分
            if (PointsCanBeUsed <= this.priceConfig.points) {
              availablePoints = PointsCanBeUsed;
            } else {
              // 如果大于积分的时候  直接使用全部积分
              availablePoints = this.priceConfig.points;
            }
          }
        } else if (this.priceConfig.offlineDeductionPropertyType == 2) {
          if (bilizongdikou <= this.priceConfig.points) {
            availablePoints = bilizongdikou;
          } else {
            availablePoints = this.priceConfig.points;
          }
        }
      }
      this.availablePoints = availablePoints;
      // 如何用户积分余额小于抵扣比例的时
      // if(this.priceConfig.points >= this.priceConfig.proportion) {
      //  // 固定值默认
      //  if(this.priceConfig.type == 0) {
      //  // 如何输入的金额不足配置的抵扣的金额
      //   if(this.earnPoints <= this.priceConfig.deductNum) {
      // 	  // 如果可抵扣积分小于现在的积分余额
      // 	  	availablePoints = 0
      //   } else {
      // 	  // 如果总可抵扣金额 小于 总积分
      // 	  if(this.priceConfig.deductNum * this.priceConfig.proportion < this.priceConfig.points) {
      // 	  	availablePoints = this.priceConfig.deductNum * this.priceConfig.proportion
      // 	  } else {
      // 	  	availablePoints = this.priceConfig.points
      // 	  }
      //   }

      //  } else {
      //   // 按比例抵扣模式
      //   if(this.earnPoints * this.priceConfig.deductionRatio *  >= this.priceConfig.points) {
      // 	 availablePoints = this.priceConfig.points
      //   } else {
      // 	  availablePoints = this.earnPoints * this.priceConfig.deductionRatio
      //   }
      //  }
      // }
      this.availablePoints = availablePoints;
    },
    openkeyboard() {
      this.$refs.cukeyboard.open();
    },
    getPayTypeName(type) {
      switch (type) {
        case "pay_weixin":
          return "微信支付";
        case "pay_yue":
          return "余额支付";
        case "pay_ls":
          return "快捷支付";
      }
    },
    onInput(key) {
      const regex = /^(\d+)(\.\d{0,2})?$/;
      if (!regex.test(this.payPrice + key)) return;
      this.payPrice += key;
    },

    initUser() {
      getUserInfo()
        .then((res) => {
          if (res.code === 401) {
            uni.showToast({
              title: "您的登录已过期，请重新登录",
              icon: "none",
            });
            uni.clearStorage();
            this.showloginJs();
            // return;
          } else {
            this.userInfo = res.data;
            uni.setStorageSync("userInfo", res.data);

            this.fastPaymentDiscountMethods(this.ebMerId);
            // this.aaaa = true;
            uni.hideLoading();
            this.showzhezhao = false;
          }
        })
        .catch((err) => {
          console.error("获取用户信息失败", err);
        });
    },
    showloginJs() {
      let that = this;
      uni.login({
        provider: "weixin",
        success: (res) => {
          if (res.code) {
            that.autoLogin(res.code);
          } else {
            console.error("登录失败:", res.errMsg);
            uni.showToast({
              title: "微信登录失败，请稍后再试",
              icon: "none",
            });
          }
        },
        fail: (err) => {
          console.error("登录失败:", err);
          uni.showToast({
            title: "微信登录失败，请稍后再试",
            icon: "none",
          });
        },
      });
    },
    /* 免登录-每个界面调用 */
    /*     async autoLogin(code) {
      let that = this;
      wx.getUserInfo({
        success(res) {
          const { nickName, avatarUrl, gender } = res.userInfo;
          programlogin({ code, avatar: avatarUrl, nickName, sex: gender }).then((response) => {
            const data = response.data;
            console.log("🚀 ~ programlogin ~ data:", data);
            that.authKey = data.key;
            if (data.type === "login") {
              uni.setStorageSync("uid", data.uid);
              uni.setStorageSync("token", data.token);
              uni.setStorageSync("userInfo_data", data);
              uni.setStorageSync("openID", data.key);
              that.initUser();
            } else {
              console.log("@@@@@@@@@@@@@@@-88888888888888");
              uni.showModal({
                title: "提示",
                content: "您的登录已过期或未登录，请重新登录。",
                success: (res) => {
                  if (res.confirm) {
                    uni.clearStorage();
                    uni.setStorageSync("ebMerId", that.ebMerId);
                    uni.setStorageSync("userType", that.userType);
                    uni.switchTab({
                      url: "/pages_h5/myCenter/index?merId=" + that.ebMerId, // 假设登录页面的路径为 /pages_h5/login/index
                    });
                  }
                },
              });
            }
          });
        },
        fail: () => {
          uni.showToast({
            title: "您需要授权，才能获取您的信息！",
          });
        },
      });
    }, */
    async logggggin() {
      uni.showLoading({
        title: "加载中",
      });
      this.showzhezhao = true;
      var e = await getUserInfo();
      if (e.code == 401) {
        this.showloginJs();
      } else {
        this.userInfo = e.data;
        uni.setStorageSync("userInfo", this.userInfo);
        uni.hideLoading();
        this.showzhezhao = false;
      }
    },
    async handleClose() {
      let that = this;

      if (!this.payPrice) {
        uni.showToast({
          title: "请输入具体金额",
          icon: "none",
        });
        return false;
      }
      if (this.payPrice <= 0) {
        uni.showToast({
          title: "请输入大于0的金额",
          icon: "none",
        });
        return false;
      }
      if (this.payPrice >= 50000) {
        uni.showToast({
          title: "金额过大",
          icon: "none",
        });
        return false;
      }
      if (this.orderType === "pay_yue" && Number(this.userInfo.nowMoney || 0) < this.allPrice) {
        uni.showToast({
          title: "请先充值",
          icon: "none",
        });
        return false;
      }
      this.loading = true;
      let bbcc = parseFloat(this.payPrice) * parseFloat(this.formData.lsSplittingBl) * parseFloat(this.fanli);
      console.log("🚀 ~ this.fanli:", this.fanli);
      console.log("🚀 ~ this.formData.lsSplittingBl:", this.formData.lsSplittingBl);
      console.log("🚀 ~ this.totalPrice:", this.payPrice);
      let params = {
        /*   gainIntegral: this.userInfo.isComunityVip != 1 ? this.integralGive : 0, */
        comunityIntegral: /* this.discountData.type == 2 && this.userInfo.isComunityVip == 1 ? this.formData.comunityIntegralUse : 0 */ this.availablePoints.toFixed(2),
        useIntegral: 0,
        deductionPrice: /* this.formData.comunityIntegralDeduction */ (this.availablePoints / this.priceConfig.integralPropertyConversion).toFixed(2),
        discountType: /* this.discountData.type */ "",
        ebComunityHouseId: /* this.discountData.ebComunityHouseId */ 0,
        ebComunityHouseName: /* this.discountData.address */ "",
        ebMerId: this.ebMerId,
        ebMerName: this.formData.merName,
        mark: this.mark,
        payPrice: /* this.allPrice */ (this.earnPoints - this.availablePoints / this.priceConfig.integralPropertyConversion).toFixed(2),
        uid: uni.getStorageSync("uid"),
        totalPrice: this.payPrice,
        payType: "lszfxcx",
        returnIntegral: parseFloat(this.payPrice) * parseFloat(this.formData.lsSplittingBl) * parseFloat(this.fanli),
        // payType: this.getPayType(this.orderType),
      };
      fastPayment(params)
        .then((obj) => {
          let leshua = obj.data.leshuaPayRequest.leshua_order_id;
          uni.requestPayment({
            timeStamp: obj.data.jsConfig.timeStamp, //后端返回的时间戳
            nonceStr: obj.data.jsConfig.nonceStr, //后端返回的随机字符串
            package: obj.data.jsConfig.packages, //后端返回的prepay_id
            signType: "RSA", //后端签名算法,根据后端来,后端MD5这里即为MD5
            paySign: obj.data.jsConfig.paySign, //后端返回的签名
            payCompletedPageOptions: {
              showNavBackButton: true,
            },
            success(res) {
              console.log("用户支付扣款成功", res);
              res.payCompletedPage.onUnload((dawd) => {
                console.log(dawd);
                console.log("🚀 ~ success ~ that.discountData.type :", that.discountData.type);
                console.log("🚀 ~ success ~ that.integralGive:", that.integralGive);

                if (that.integralGive >= 0.1 && that.userInfo.isComunityVip != 1) {
                  uni.showLoading({
                    title: "加载中",
                  });
                  uni.navigateTo({
                    url: "/pages_h5/index/components/paybill_end?integralGive=" + that.integralGive,
                  });
                  uni.hideLoading();
                } else {
                  uni.switchTab({
                    url: "/pages_h5/index/index", // 点击左上角返回按钮，会触发支付回调页onUnload 事件，在 onUnload 事件触发时可以跳转到别的页面
                  });
                }
              });
              // uni.request({
              //   url: "https://www.wantongkonggu.cn/api/frontApph7/order/get/pay/lsReceipt",
              //   method: "GET",
              //   data: { leshuaOrderId: leshua },
              //   success: (resd) => {
              //     uni.request({
              //       url: "https://www.wantongkonggu.cn/api/frontApph7/pay/LsQueryPayResult",
              //       method: "GET",
              //       data: { orderNo: resd.data.data.orderId },
              //       success(ressss) { },
              //     });
              //   },
              //   fail: (err) => {
              //     that.errdata = JSON.stringify(err);
              //   },
              //   complete: (ress) => { },
              // });
            },
            fail(res) {
              console.log("用户支付扣款失败", res);
            },
          });
        })
        .catch((err) => {
          console.log("🚀 ~ err:", err);
          this.loading = false;
          uni.showToast({
            title: "商户资料审核中，暂未开通支付",
            icon: "none",
          });
        });
    },

    getMerInfoByids(id) {
      getMerInfoByid({ id }).then((res) => {
        this.formData = res.data.ebMer || {};
        this.priceConfig.offlineDeductionPropertyType = res.data.ebMer.offlineDeductionPropertyType;
        this.priceConfig.offlineIntegralDeductionPropertyValue = parseFloat(res.data.ebMer.offlineIntegralDeductionPropertyValue);
        console.log(this.priceConfig.offlineIntegralDeductionPropertyValue);
        this.priceConfig.integralPropertyConversion = res.data.ebMer.integralPropertyConversion;
        this.priceConfig.offlineIntegralProperty = parseFloat(res.data.ebMer.offlineIntegralProperty);
      });
    },
    fastPaymentDiscountMethods(id) {
      fastPaymentDiscountMethod({
        ebMerId: id,
        userId: uni.getStorageSync("uid"),
      }).then((res) => {
        this.jifen = res.data.frontComunityInteralPoVo.accumulationFund || 0;
        this.formData = {
          ...this.formData,
          ...res.data,
        };
      });
    },
  },
};
</script>

<style lang="less" scoped>
.payment-container {
  font-family: "PingFang SC";
  padding: 0 20rpx;

  .merchant-info {
    padding-top: 20rpx;
    display: flex;
    align-items: center;
    margin-bottom: 1rem;

    .merchant-avatar {
      width: 3rem;
      height: 3rem;
      border-radius: 10%;
      margin-right: 0.5rem;
    }

    .merchant-name {
      flex: 1;
      font-size: 0.9rem;
      font-weight: bold;
    }
  }

  .payment-input {
    background-color: #fff;
    border-radius: 10rpx;
    position: relative;
    padding: 0.8rem;
    display: flex;
    align-items: center;
    border-radius: 20rpx;

    .input-field {
      flex: 1;
      font-size: 1.8rem;
      padding-left: 0.5rem;
      border: none;
      outline: none;
      height: 50px;
    }

    .delete-icon {
      position: absolute;
      top: 50%;
      right: 0.8rem;
      transform: translateY(-50%);
      width: 24px;
      height: 24px;
    }
  }

  .remark-input {
    padding: 0.8rem;
    background-color: #fff;
    border-radius: 20rpx;
    margin: 20rpx 0;

    .input-field {
      width: 100%;
      padding: 0.5rem;
      border: none;
      outline: none;
    }
  }

  .discount-details {
    padding: 0.8rem;
    margin-top: 1rem;
    background-color: #fff;
    border-radius: 20rpx;

    .discount-item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 0.8rem;

      &:last-child {
        margin-bottom: 0;
      }

      .discount-title {
        font-size: 0.8rem;
        color: rgba(0, 0, 0, 0.6);
      }

      .discount-value {
        font-size: 1rem;
        color: #000;
      }
    }

    .total-amount {
      display: flex;
      justify-content: flex-end;
      margin-top: 1rem;
      align-items: center;

      .total-label {
        font-size: 0.8rem;
        color: rgba(0, 0, 0, 0.6);
        margin-right: 0.5rem;
      }

      .total-value {
        font-size: 1.8rem;
        color: #ff9500;
      }
    }
  }

  .payment-popup {
    padding: 1rem;
  }
}

.fonthui {
  color: #999;
}
</style>
